{% extends "public/base.html" %}

{% block title %}{{ publication.custom_title or scale.title }} - 测评进行中{% endblock %}

{% block extra_css %}
<style>
/* 隐藏导航栏 */
.navbar {
    display: none !important;
}

/* 重置body样式 */
body {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    min-height: 100vh;
    margin: 0;
    padding: 20px 0;
}

/* 重置容器样式 */
.main-container {
    min-height: auto !important;
    padding: 0 !important;
}

.assessment-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 15px;
}

/* 覆盖基础模板的卡片样式 */
.question-card {
    background: white !important;
    border-radius: 15px !important;
    padding: 2rem !important;
    margin-bottom: 2rem !important;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1) !important;
    transition: all 0.3s ease !important;
}

/* 覆盖基础模板的选项样式 */
.option-item {
    background: #f8f9fa !important;
    border: 2px solid transparent !important;
    border-radius: 12px !important;
    padding: 1rem 1.5rem !important;
    margin-bottom: 0.75rem !important;
    cursor: pointer !important;
    transition: all 0.3s ease !important;
    display: flex !important;
    align-items: center !important;
    position: relative !important;
}

.option-item:hover {
    background: #e9ecef !important;
    border-color: #007bff !important;
    transform: translateX(5px) !important;
}

.option-item.selected {
    background: rgba(0, 123, 255, 0.1) !important;
    border-color: #007bff !important;
    color: #007bff !important;
    transform: translateX(5px) !important;
}

.progress-section {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    position: sticky;
    top: 20px;
    z-index: 100;
}

.progress-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.progress-text {
    font-weight: 500;
    color: #495057;
}

.time-info {
    font-size: 0.9rem;
    color: #6c757d;
}

.question-container {
    background: white;
    border-radius: 15px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    transition: all 0.3s ease;
}

.question-header {
    border-bottom: 2px solid #f8f9fa;
    padding-bottom: 1rem;
    margin-bottom: 2rem;
}

.question-number {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    margin-right: 1rem;
    flex-shrink: 0;
}

.question-text {
    font-size: 1.1rem;
    font-weight: 500;
    color: #333;
    line-height: 1.6;
}

.required-indicator {
    color: #dc3545;
    margin-left: 0.25rem;
}

.options-container {
    margin: 1.5rem 0;
}

.option-item {
    background: #f8f9fa;
    border: 2px solid transparent;
    border-radius: 12px;
    padding: 1rem 1.5rem;
    margin-bottom: 0.75rem;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    position: relative;
}

.option-item:hover {
    background: #e9ecef;
    border-color: #007bff;
    transform: translateX(5px);
}

.option-item.selected {
    background: rgba(0, 123, 255, 0.1);
    border-color: #007bff;
    color: #007bff;
    transform: translateX(5px);
}

.option-item.selected::after {
    content: "✓";
    position: absolute;
    right: 1rem;
    font-weight: bold;
    color: #007bff;
}

.option-radio {
    margin-right: 1rem;
    transform: scale(1.2);
}

.option-text {
    flex: 1;
    font-weight: 500;
}

.option-value {
    font-size: 0.9rem;
    color: #6c757d;
    margin-left: 1rem;
}

.navigation-section {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: sticky;
    bottom: 20px;
    z-index: 100;
}

.nav-button {
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
    min-width: 120px;
}

.btn-prev {
    background: #6c757d;
    border: none;
    color: white;
}

.btn-prev:hover {
    background: #5a6268;
    color: white;
    transform: translateY(-1px);
}

.btn-next {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    border: none;
    color: white;
}

.btn-next:hover {
    background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
    color: white;
    transform: translateY(-1px);
}

.btn-submit {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    border: none;
    color: white;
}

.btn-submit:hover {
    background: linear-gradient(135deg, #20c997 0%, #17a2b8 100());
    color: white;
    transform: translateY(-1px);
}

.question-nav {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.question-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #dee2e6;
    cursor: pointer;
    transition: all 0.3s ease;
}

.question-dot.answered {
    background: #28a745;
}

.question-dot.current {
    background: #007bff;
    transform: scale(1.3);
}

.basic-info-section {
    background: white;
    border-radius: 15px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.info-form .form-group {
    margin-bottom: 1.5rem;
}

.info-form label {
    font-weight: 500;
    color: #495057;
    margin-bottom: 0.5rem;
}

.info-form .form-control, .info-form .form-select {
    border-radius: 8px;
    border: 2px solid #e9ecef;
    padding: 0.75rem 1rem;
}

.info-form .form-control:focus, .info-form .form-select:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.save-reminder {
    background: #fff3cd;
    border: 1px solid #ffeaa7;
    border-radius: 8px;
    padding: 1rem;
    margin: 1rem 0;
    text-align: center;
}

.auto-save-indicator {
    position: fixed;
    top: 20px;
    right: 20px;
    background: #28a745;
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.9rem;
    opacity: 0;
    transition: opacity 0.3s ease;
    z-index: 1000;
}

.auto-save-indicator.show {
    opacity: 1;
}

@media (max-width: 768px) {
    .assessment-container {
        padding: 0 1rem;
    }
    
    .question-container {
        padding: 1.5rem;
    }
    
    .navigation-section {
        flex-direction: column;
        gap: 1rem;
    }
    
    .nav-button {
        width: 100%;
    }
    
    .question-nav {
        order: -1;
        margin-bottom: 1rem;
    }
    
    .progress-section {
        position: static;
    }
    
    .navigation-section {
        position: static;
    }
}

.fade-in-up {
    animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>
{% endblock %}

{% block content %}
<div class="assessment-container">
    <!-- 进度条 -->
    <div class="progress-section">
        <div class="progress-info">
            <div class="progress-text">
                <span id="current-question">1</span> / <span id="total-questions">{{ questions|length }}</span>
            </div>
            <div class="time-info">
                <i class="bi bi-clock me-1"></i>
                <span id="elapsed-time">00:00</span>
            </div>
        </div>
        <div class="progress" style="height: 8px;">
            <div class="progress-bar" id="progress-bar" style="width: 0%"></div>
        </div>
        
        <!-- 题目导航点 -->
        <div class="question-nav mt-2">
            {% for question in questions %}
            <div class="question-dot" data-question="{{ loop.index }}" 
                 onclick="goToQuestion({{ loop.index }})" 
                 title="第{{ loop.index }}题"></div>
            {% endfor %}
        </div>
    </div>

    <!-- 基本信息收集（仅在第一题前显示） -->
    <div class="basic-info-section" id="basic-info-section">
        <h4 class="mb-3">
            <i class="bi bi-person me-2"></i>
            基本信息（可选）
        </h4>
        <p class="text-muted mb-4">为了提供更准确的分析结果，请填写以下基本信息。所有信息都是匿名的，仅用于统计分析。</p>
        
        <form class="info-form" id="basic-info-form">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="age">年龄</label>
                        <select class="form-select" id="age" name="age">
                            <option value="">请选择</option>
                            <option value="18-25">18-25岁</option>
                            <option value="26-35">26-35岁</option>
                            <option value="36-45">36-45岁</option>
                            <option value="46-55">46-55岁</option>
                            <option value="55+">55岁以上</option>
                        </select>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="gender">性别</label>
                        <select class="form-select" id="gender" name="gender">
                            <option value="">请选择</option>
                            <option value="male">男</option>
                            <option value="female">女</option>
                            <option value="other">其他</option>
                        </select>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="education">教育程度</label>
                        <select class="form-select" id="education" name="education">
                            <option value="">请选择</option>
                            <option value="初中及以下">初中及以下</option>
                            <option value="高中/中专">高中/中专</option>
                            <option value="大专">大专</option>
                            <option value="本科">本科</option>
                            <option value="硕士">硕士</option>
                            <option value="博士">博士</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="text-center mt-3">
                <button type="button" class="btn btn-primary" onclick="startQuestions()">
                    <i class="bi bi-arrow-right me-2"></i>
                    开始答题
                </button>
            </div>
        </form>
    </div>

    <!-- 题目容器 -->
    <div id="questions-container" style="display: none;">
        {% for question in questions %}
        <div class="question-container fade-in-up" id="question-{{ loop.index }}" 
             style="{% if loop.index > 1 %}display: none;{% endif %}" data-question-index="{{ loop.index }}">
            
            <div class="question-header">
                <div class="d-flex align-items-center">
                    <div class="question-number">{{ loop.index }}</div>
                    <div class="question-text">
                        {{ question.question_text }}
                        {% if question.is_required %}
                        <span class="required-indicator">*</span>
                        {% endif %}
                    </div>
                </div>
            </div>
            
            <div class="options-container">
                {% if question.question_type == 'single' %}
                    {% for option in question.options %}
                    <div class="option-item" onclick="selectOption(currentQuestionIndex, '{{ option.option_key }}', {{ loop.index0 }})">
                        <input type="radio" name="question_{{ question.id }}" 
                               value="{{ option.option_key }}" 
                               class="option-radio" 
                               id="option_{{ question.id }}_{{ loop.index0 }}">
                        <div class="option-text">{{ option.option_text }}</div>
                        {% if option.option_value is not none %}
                        <div class="option-value">({{ option.option_value }}分)</div>
                        {% endif %}
                    </div>
                    {% endfor %}
                {% elif question.question_type == 'multiple' %}
                    {% for option in question.options %}
                    <div class="option-item" onclick="toggleOption(currentQuestionIndex, '{{ option.option_key }}', {{ loop.index0 }})">
                        <input type="checkbox" name="question_{{ question.id }}" 
                               value="{{ option.option_key }}" 
                               class="option-radio" 
                               id="option_{{ question.id }}_{{ loop.index0 }}">
                        <div class="option-text">{{ option.option_text }}</div>
                        {% if option.option_value is not none %}
                        <div class="option-value">({{ option.option_value }}分)</div>
                        {% endif %}
                    </div>
                    {% endfor %}
                {% elif question.question_type == 'text' %}
                    <textarea class="form-control" 
                              name="question_{{ question.id }}" 
                              id="text_{{ question.id }}"
                              rows="4" 
                              placeholder="请输入您的答案..."
                              onchange="saveTextAnswer({{ loop.index }}, this.value)"></textarea>
                {% elif question.question_type == 'scale' %}
                    <div class="scale-container">
                        <div class="scale-labels d-flex justify-content-between mb-2">
                            <span>完全不同意</span>
                            <span>完全同意</span>
                        </div>
                        <input type="range" class="form-range" 
                               name="question_{{ question.id }}"
                               id="scale_{{ question.id }}"
                               min="1" max="7" value="4"
                               onchange="saveScaleAnswer({{ loop.index }}, this.value)">
                        <div class="text-center mt-2">
                            <span class="badge bg-primary" id="scale_value_{{ question.id }}">4</span>
                        </div>
                    </div>
                {% endif %}
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- 导航按钮 -->
    <div class="navigation-section" id="navigation-section" style="display: none;">
        <button class="btn btn-prev nav-button" id="prev-btn" onclick="previousQuestion()" disabled>
            <i class="bi bi-arrow-left me-2"></i>
            上一题
        </button>
        
        <div class="save-reminder">
            <i class="bi bi-cloud-check me-2"></i>
            答案会自动保存
        </div>
        
        <button class="btn btn-next nav-button" id="next-btn" onclick="nextQuestion()">
            下一题
            <i class="bi bi-arrow-right ms-2"></i>
        </button>
        
        <button class="btn btn-submit nav-button" id="submit-btn" onclick="submitAssessment()" style="display: none;">
            <i class="bi bi-check-circle me-2"></i>
            提交测评
        </button>
    </div>
</div>

<!-- 自动保存提示 -->
<div class="auto-save-indicator" id="auto-save-indicator">
    <i class="bi bi-cloud-check me-1"></i>
    已自动保存
</div>

<!-- 提交确认模态框 -->
<div class="modal fade" id="submitModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-check-circle me-2"></i>
                    提交测评
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <i class="bi bi-question-circle display-6 text-warning"></i>
                </div>
                <h6 class="text-center mb-3">确认提交测评？</h6>
                <div class="alert alert-info">
                    <div class="row text-center">
                        <div class="col-4">
                            <strong id="answered-count">0</strong><br>
                            <small>已答题目</small>
                        </div>
                        <div class="col-4">
                            <strong id="total-count">{{ questions|length }}</strong><br>
                            <small>总题目数</small>
                        </div>
                        <div class="col-4">
                            <strong id="completion-rate">0%</strong><br>
                            <small>完成率</small>
                        </div>
                    </div>
                </div>
                <p class="text-center text-muted mb-0">
                    提交后将生成您的测评报告，无法再次修改答案。
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-arrow-left me-2"></i>继续答题
                </button>
                <button type="button" class="btn btn-success" onclick="confirmSubmit()">
                    <i class="bi bi-check-circle me-2"></i>确认提交
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 加载状态 -->
<div class="text-center py-5 d-none" id="loading-indicator">
    <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">提交中...</span>
    </div>
    <p class="mt-2 text-muted">正在生成您的测评报告...</p>
</div>
{% endblock %}

{% block extra_js %}
<script>
const publicationToken = '{{ publication.publication_token }}';
const scaleId = {{ scale.id|default(0) }};
const totalQuestions = {{ questions|length }};
let currentQuestionIndex = 1;
let answers = {};
let basicInfo = {};
let startTime = null;
let assessmentId = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeAssessment();
    startTimer();
});

// 初始化测评
function initializeAssessment() {
    startTime = new Date();
    
    // 尝试恢复之前的进度
    const savedProgress = localStorage.getItem(`assessment_${publicationToken}`);
    if (savedProgress) {
        const progress = JSON.parse(savedProgress);
        answers = progress.answers || {};
        basicInfo = progress.basicInfo || {};
        currentQuestionIndex = progress.currentQuestion || 1;
        
        // 恢复基本信息
        if (Object.keys(basicInfo).length > 0) {
            Object.keys(basicInfo).forEach(key => {
                const element = document.getElementById(key);
                if (element) {
                    element.value = basicInfo[key];
                }
            });
        }
        
        // 恢复答案
        Object.keys(answers).forEach(questionIndex => {
            restoreAnswer(questionIndex, answers[questionIndex]);
        });
        
        updateProgress();
    }
}

// 开始答题
function startQuestions() {
    // 收集基本信息
    const form = document.getElementById('basic-info-form');
    const formData = new FormData(form);
    
    for (let [key, value] of formData.entries()) {
        if (value) {
            basicInfo[key] = value;
        }
    }
    
    // 隐藏基本信息，显示题目
    document.getElementById('basic-info-section').style.display = 'none';
    document.getElementById('questions-container').style.display = 'block';
    document.getElementById('navigation-section').style.display = 'flex';
    
    // 保存进度
    saveProgress();
    
    // 显示第一题
    showQuestion(1);
}

// 显示指定题目
function showQuestion(questionIndex) {
    // 隐藏所有题目
    document.querySelectorAll('.question-container').forEach(container => {
        container.style.display = 'none';
    });
    
    // 显示当前题目
    const currentQuestion = document.getElementById(`question-${questionIndex}`);
    if (currentQuestion) {
        currentQuestion.style.display = 'block';
        addFadeInAnimation(currentQuestion);
    }
    
    currentQuestionIndex = questionIndex;
    updateProgress();
    updateNavigation();
    
    // 滚动到顶部
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// 选择单选选项
function selectOption(questionIndex, optionKey, optionIndex) {
    const questionContainer = document.getElementById(`question-${questionIndex}`);
    const options = questionContainer.querySelectorAll('.option-item');
    const radio = questionContainer.querySelector(`input[value="${optionKey}"]`);
    
    // 清除所有选中状态
    options.forEach(option => option.classList.remove('selected'));
    
    // 设置当前选中
    options[optionIndex].classList.add('selected');
    radio.checked = true;
    
    // 保存答案
    answers[questionIndex] = optionKey;
    saveProgress();
    showAutoSaveIndicator();
}

// 切换多选选项
function toggleOption(questionIndex, optionKey, optionIndex) {
    const questionContainer = document.getElementById(`question-${questionIndex}`);
    const option = questionContainer.querySelectorAll('.option-item')[optionIndex];
    const checkbox = questionContainer.querySelector(`input[value="${optionKey}"]`);
    
    // 切换选中状态
    if (checkbox.checked) {
        checkbox.checked = false;
        option.classList.remove('selected');
    } else {
        checkbox.checked = true;
        option.classList.add('selected');
    }
    
    // 收集所有选中的选项
    const selectedOptions = [];
    questionContainer.querySelectorAll('input[type="checkbox"]:checked').forEach(cb => {
        selectedOptions.push(cb.value);
    });
    
    // 保存答案
    answers[questionIndex] = selectedOptions;
    saveProgress();
    showAutoSaveIndicator();
}

// 保存文本答案
function saveTextAnswer(questionIndex, value) {
    answers[questionIndex] = value;
    saveProgress();
    showAutoSaveIndicator();
}

// 保存量表答案
function saveScaleAnswer(questionIndex, value) {
    answers[questionIndex] = value;
    document.getElementById(`scale_value_${document.querySelector(`#question-${questionIndex} input[type="range"]`).name.split('_')[1]}`).textContent = value;
    saveProgress();
    showAutoSaveIndicator();
}

// 恢复答案
function restoreAnswer(questionIndex, answer) {
    const questionContainer = document.getElementById(`question-${questionIndex}`);
    if (!questionContainer) return;
    
    const questionType = questionContainer.querySelector('input, textarea, .form-range');
    if (!questionType) return;
    
    if (questionType.type === 'radio') {
        // 单选题
        const radio = questionContainer.querySelector(`input[value="${answer}"]`);
        if (radio) {
            radio.checked = true;
            const optionIndex = Array.from(questionContainer.querySelectorAll('input[type="radio"]')).indexOf(radio);
            questionContainer.querySelectorAll('.option-item')[optionIndex].classList.add('selected');
        }
    } else if (questionType.type === 'checkbox') {
        // 多选题
        if (Array.isArray(answer)) {
            answer.forEach(value => {
                const checkbox = questionContainer.querySelector(`input[value="${value}"]`);
                if (checkbox) {
                    checkbox.checked = true;
                    const optionIndex = Array.from(questionContainer.querySelectorAll('input[type="checkbox"]')).indexOf(checkbox);
                    questionContainer.querySelectorAll('.option-item')[optionIndex].classList.add('selected');
                }
            });
        }
    } else if (questionType.tagName === 'TEXTAREA') {
        // 文本题
        questionType.value = answer;
    } else if (questionType.type === 'range') {
        // 量表题
        questionType.value = answer;
        const valueDisplay = questionContainer.querySelector('.badge');
        if (valueDisplay) {
            valueDisplay.textContent = answer;
        }
    }
}

// 上一题
function previousQuestion() {
    if (currentQuestionIndex > 1) {
        showQuestion(currentQuestionIndex - 1);
    }
}

// 下一题
function nextQuestion() {
    if (currentQuestionIndex < totalQuestions) {
        showQuestion(currentQuestionIndex + 1);
    }
}

// 跳转到指定题目
function goToQuestion(questionIndex) {
    showQuestion(questionIndex);
}

// 更新进度
function updateProgress() {
    const progress = (currentQuestionIndex / totalQuestions) * 100;
    document.getElementById('progress-bar').style.width = `${progress}%`;
    document.getElementById('current-question').textContent = currentQuestionIndex;
    
    // 更新题目导航点
    document.querySelectorAll('.question-dot').forEach((dot, index) => {
        dot.classList.remove('current', 'answered');
        
        if (index + 1 === currentQuestionIndex) {
            dot.classList.add('current');
        } else if (answers[index + 1]) {
            dot.classList.add('answered');
        }
    });
}

// 更新导航按钮
function updateNavigation() {
    const prevBtn = document.getElementById('prev-btn');
    const nextBtn = document.getElementById('next-btn');
    const submitBtn = document.getElementById('submit-btn');
    
    // 上一题按钮
    prevBtn.disabled = currentQuestionIndex === 1;
    
    // 下一题/提交按钮
    if (currentQuestionIndex === totalQuestions) {
        nextBtn.style.display = 'none';
        submitBtn.style.display = 'block';
    } else {
        nextBtn.style.display = 'block';
        submitBtn.style.display = 'none';
    }
}

// 保存进度
function saveProgress() {
    const progress = {
        answers: answers,
        basicInfo: basicInfo,
        currentQuestion: currentQuestionIndex,
        timestamp: new Date().toISOString()
    };
    
    localStorage.setItem(`assessment_${publicationToken}`, JSON.stringify(progress));
}

// 显示自动保存提示
function showAutoSaveIndicator() {
    const indicator = document.getElementById('auto-save-indicator');
    indicator.classList.add('show');
    
    setTimeout(() => {
        indicator.classList.remove('show');
    }, 2000);
}

// 提交测评
function submitAssessment() {
    // 统计完成情况
    const answeredCount = Object.keys(answers).length;
    const completionRate = Math.round((answeredCount / totalQuestions) * 100);
    
    document.getElementById('answered-count').textContent = answeredCount;
    document.getElementById('completion-rate').textContent = `${completionRate}%`;
    
    // 显示确认模态框
    const modal = new bootstrap.Modal(document.getElementById('submitModal'));
    modal.show();
}

// 确认提交
function confirmSubmit() {
    const modal = bootstrap.Modal.getInstance(document.getElementById('submitModal'));
    modal.hide();
    
    // 显示加载状态
    document.getElementById('loading-indicator').classList.remove('d-none');
    document.querySelector('.assessment-container').style.display = 'none';
    
    // 计算测评时长
    const duration = Math.floor((new Date() - startTime) / 1000);
    
    // 准备提交数据
    const submitData = {
        basic_info: basicInfo,
        answers: Object.keys(answers).map(questionIndex => ({
            question_id: getQuestionId(questionIndex),
            answer: answers[questionIndex]
        })),
        duration: duration
    };
    
    // 提交到服务器
    apiRequest(`/public/scale/${publicationToken}/assess`, {
        method: 'POST',
        body: JSON.stringify(submitData)
    })
    .then(response => {
        if (response.code === 200) {
            // 清除本地保存的进度
            localStorage.removeItem(`assessment_${publicationToken}`);
            
            // 跳转到结果页面
            window.location.href = `/public/scale/${publicationToken}/result/${response.data.assessment_id}`;
        } else {
            throw new Error(response.message || '提交失败');
        }
    })
    .catch(error => {
        console.error('提交失败:', error);
        document.getElementById('loading-indicator').classList.add('d-none');
        document.querySelector('.assessment-container').style.display = 'block';
        showResult(false, '提交失败: ' + error.message);
    });
}

// 获取题目ID
function getQuestionId(questionIndex) {
    const questionContainer = document.getElementById(`question-${questionIndex}`);
    const input = questionContainer.querySelector('input, textarea, .form-range');
    if (input && input.name) {
        return parseInt(input.name.split('_')[1]);
    }
    return questionIndex;
}

// 计时器
function startTimer() {
    setInterval(() => {
        if (startTime) {
            const elapsed = Math.floor((new Date() - startTime) / 1000);
            const minutes = Math.floor(elapsed / 60);
            const seconds = elapsed % 60;
            document.getElementById('elapsed-time').textContent = 
                `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
    }, 1000);
}

// 键盘快捷键
document.addEventListener('keydown', function(event) {
    if (event.key === 'ArrowLeft' && !event.target.matches('input, textarea')) {
        previousQuestion();
    } else if (event.key === 'ArrowRight' && !event.target.matches('input, textarea')) {
        nextQuestion();
    } else if (event.key === 'Enter' && event.ctrlKey) {
        if (currentQuestionIndex === totalQuestions) {
            submitAssessment();
        } else {
            nextQuestion();
        }
    }
});

// 防止意外离开页面
window.addEventListener('beforeunload', function(event) {
    if (Object.keys(answers).length > 0) {
        event.preventDefault();
        event.returnValue = '您的测评进度尚未提交，确定要离开吗？';
    }
});

// 页面可见性变化时自动保存
document.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'hidden') {
        saveProgress();
    }
});
</script>
{% endblock %}